<template>
    <div class="register-box">
        <van-nav-bar :title="type === '1'? '注册' : '找回密码'" left-text="返回" left-arrow @click-left="goBack" />
        <van-form>
            <van-cell-group inset class="register-cell-group">
                <van-field 
                    label="+86" 
                    placeholder="请输入手机号" 
                    v-model="registerInfo.donatorPhone" 
                    type="tel" 
                    :rules="[{ required: true, message: '请输入手机号' }, { validator: validator1, message: '请输入正确的手机号' }]" 
                />
                <van-field 
                    label="密码" 
                    type="password" 
                    placeholder="设置登入密码" 
                    v-model="registerInfo.donatorPassword" 
                    maxlength="15" 
                    :rules="[{ required: true, message: '请输入密码' }, { validator: validator2, message: '请输入正确的密码' }]" 
                />
                <van-notice-bar left-icon="info-o">
                    密码需由6-15位英文字母、数字构成
                </van-notice-bar>
                <van-field 
                    label="确认密码" 
                    type="password" 
                    placeholder="确认登入密码" 
                    v-model="registerInfo.confirmPassword" 
                    maxlength="15"
                    :rules="[{ required: true, message: '请确认密码' }, { validator: validator2, message: '请输入正确的密码' }]" 
                />
                <van-field 
                    clearable 
                    center 
                    placeholder="手机验证码" 
                    label="验证码" 
                    v-model="registerInfo.code" 
                    :rules="[{ required: true, message: '请输入验证码' }]"
                >
                    <template #button>
                        <van-button size="small" type="primary" @click="toGetCode" :disabled="isSendingCode || countdown > 0">{{ countdown > 0 ? `重新发送（${countdown}）` : '获取验证码' }}</van-button>
                    </template>
                </van-field>
            </van-cell-group>
        </van-form>
        <van-button type="primary" block class="register-btn" round @click="toRegister">{{ type === '1'? '立即注册' : '提交' }}</van-button>
    </div>
</template>

<script lang="ts" setup>
import { showSuccessToast, showFailToast } from 'vant';
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { useRouter } from 'vue-router';
import { donatorApi } from '../../api/app';

const router = useRouter();
/** 用户注册信息 */
const registerInfo = ref({
    donatorPhone: '',
    donatorPassword: '',
    confirmPassword: '',
    code: ''
})
/** 页面类型：1-注册 0-找回密码 */
const type = ref('1');
/** 倒计时 */
let countdown = ref(0);
const isSendingCode = ref(false);

onMounted(() => {
    const route = useRoute();
    type.value = route.params.type as string;
})

/** 返回 */
const goBack = () => {
    router.back();
}

/** 正则校验 */
const validator1 = (val: string) => /1\d{10}/.test(val); // 手机号正则
const validator2 = (val: string) => /^[a-zA-Z0-9]{6,15}$/.test(val); // 密码正则

/** 注册 */
const toRegister = async () => {
    // 校验
    if (registerInfo.value.donatorPassword !== registerInfo.value.confirmPassword) {
        showFailToast('两次密码输入不一致');
        return;
    }
    if (!validator1(registerInfo.value.donatorPhone)) {
        showFailToast('请输入正确的手机号');
        return;
    }
    if (!validator2(registerInfo.value.donatorPassword)) {
        showFailToast('密码需由6-15位英文字母、数字构成');
        return;
    }
    if (registerInfo.value.code.length !== 4) {
        showFailToast('请输入4位验证码');
        return;
    }
    if (type.value === '1') {
        donatorApi.toRegister(registerInfo.value).then((res: any) => {
            if (res == -1) {
                showFailToast('验证码错误或已失效');
            } else if (res == 1){
                showSuccessToast('注册成功');
            } else {
                showFailToast('注册失败');
            }
        })
    } else {
        donatorApi.toChangePassword(registerInfo.value).then((res: any) => {
            if (res == 1) {
                showSuccessToast('密码修改成功');
            } else if (res == -1) {
                showFailToast('验证码错误或已失效');
            } else if (res == -2) {
                showFailToast('该手机号不存在');
            } else {
                showFailToast('密码修改失败');
            }
        })
    }
}

/** 获取验证码 */
const toGetCode = () => {
    donatorApi.sendCode({ donatorPhone: registerInfo.value.donatorPhone, type: type.value }).then((res: any) => {
        if (res == "该手机号已注册") {
            showFailToast('该手机号已注册');
        } else {
            showSuccessToast('验证码发送成功');
            // 设置倒计时
            countdown.value = 60;
            isSendingCode.value = true;
            // 倒计时效果
            const countdownInterval = setInterval(() => {
                countdown.value --;
                if (countdown.value <= 0) {
                    clearInterval(countdownInterval);
                    isSendingCode.value = false;
                }
            }, 1000)
        }
    })
}
</script>

<style lang="less">
.register-box {
    width: 100vw;
    height: 100vh;
    background-color: rgba(237, 231, 231, 0.422);
    display: flex;
    flex-direction: column;

    .register-cell-group {
        margin-top: 10px;
    }

    .register-btn {
        margin-top: 2em;
        width: 80%;
        align-self: center;
    }
}
</style>